package edu.chl.majc.travelapplication.DB;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;

/**
 * JPATravelController
 * An abstract class that's implementing basic CRUD operations for the applications entity classes.
 * Using Facade design pattern
 * @author lujoel
 */

public abstract class JPATravelController<T> implements Serializable{
    private Class<T> entityClass;
    
    public JPATravelController(Class<T> entityClass) {
        this.entityClass = entityClass;
    }
    
    protected abstract EntityManager getEntitymanager();
    protected abstract void setEntitymanager(EntityManager em);

    public void create(T entity) {
        getEntitymanager().persist(entity);
    }

    public void edit(T entity) {
        getEntitymanager().merge(entity);
    }

    public void remove(T entity) {
        getEntitymanager().remove(getEntitymanager().merge(entity));
    }

    public T find(String id) {
        return getEntitymanager().find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = getEntitymanager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntitymanager().createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = getEntitymanager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        javax.persistence.Query q = getEntitymanager().createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = getEntitymanager().getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
        cq.select(getEntitymanager().getCriteriaBuilder().count(rt));
        javax.persistence.Query q = getEntitymanager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }
    
}

